package com.resafety.rtsp2flv.utils;

import com.alibaba.fastjson.JSONObject;
import com.resafety.rtsp2flv.service.FFmpegManager;
import com.resafety.rtsp2flv.service.impl.FFmpegManagerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Rtsp转Rtmp
 */
@Component
public class RtspToRtmpUtils {

    @Autowired
    FFmpegManager manager;

    @Value("${rtsp2flv.tool.path}")
    String ffmpegPath;

    @Value("${rtsp2flv.rtmp.url}")
    String rtmpUrl;

    @Value("${rtsp2flv.flv.url}")
    String flvUrl;

    public JSONObject getRtmp(String rtsp) throws InterruptedException {
        JSONObject jsonObject=new JSONObject();
        /**随机数*/
        int max=1000,min=1;

        int num = (int) (Math.random()*(max-min)+min);
        String rtmpUrlTemp = rtmpUrl.replace("{num}", String.valueOf(num));
        String start = manager.start("process"+num, ffmpegPath+" -i " + rtsp + " -vcodec copy -acodec copy -f flv \""+rtmpUrlTemp+"\"");
        jsonObject.put("url", rtmpUrlTemp);
        String flvUrlTemp = flvUrl.replace("{num}", String.valueOf(num));
        jsonObject.put("httpurl", flvUrlTemp);
        jsonObject.put("process",start);

        /**ip*/
//        String ip="192.168.106.13";
        /**转流开始*/
//        String start = manager.start("process" + num, "ffmpeg -i " + rtsp + " -vcodec copy -acodec copy -f flv \"rtmp://"+ip+":1935/live/" + num + "\"");
//        /**输出rtmp流*/
//        jsonObject.put("url","rtmp://"+ip+":1935/live/"+num);
//        /**输出http-flv流*/
//        jsonObject.put("httpurl","http://"+ip+":8086/live?port=1935&app=live&stream="+num);
        /**用于关闭流使用*/
//        jsonObject.put("process",start);
        return jsonObject;
    }


    /**
    * @功能描述: 停止转流的进程
    * @param: [process]
    * @return: boolean
    * @author: 技术中心
    * @date: 2021/12/06 16:02
    **/
    public boolean stopProcess(String process){
        boolean stop = manager.stop(process);
        return stop;
    }

    /**
    * @功能描述: 关闭页面时停止所有视频
    * @param: []
    * @return: int
    * @author: 技术中心
    * @date: 2021/12/08 14:07
    **/
    public int stopAllProcess(){
        int i = manager.stopAll();
        return i;
    }
  
}
